<template>
    <el-card class="application-edit">
        <header class="text-center mb-4">{{ titleText }}帮助</header>
  
        <div class="application-edit__upload">
            <img-cropper-upload v-model="form.img" :config="{width: 900}" class="w-full">
                <div class="active relative" v-if="form.img">
                    <img :src="form.img" style="max-height: 250px;">
                    <span class="delete-icon">
                        <i class="el-icon-error" @click.stop="form.img = ''"></i>
                    </span>
                </div>
                <div class="default text-center" v-else>
                    <i class="iconfont icon-camera"></i>
                    <div>请添加封面图片<br/>建议尺寸：900像素*500像素</div>
                </div>
            </img-cropper-upload>
        </div>

        <!-- 标题 -->
        <input type="text" v-model="form.title" placeholder="请输入标题" class="application-edit__title border-b">

        <!-- 分类 -->
        <div class="flex items-center">
            <div class="flex items-center mr-4" v-for="(item, ind) in types" :key="ind">
                <el-cascader
                    class="mr-2 mb-4"
                    v-model="types[ind]"
                    :options="typeOptions"
                    placeholder="请选择类目"
                    :show-all-levels="false"
                    :props="{value: 'id', label: 'text', children: 'nodes'}">
                </el-cascader>
                <i class="el-icon-close mb-4" @click="types.splice(ind, 1)"></i>
            </div>

            <span @click="addCategory" class="text-blue-light mb-4 flex-no-shrink">
                <i class="el-icon-plus mr-2 text-xs"></i>添加
            </span>
        </div>

        <!-- <el-select
            class="mb-4 application-edit__tags border-b w-full"
            v-model="form.labels"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请填写标签，用回车分割">
        </el-select> -->

        <!-- 富文本 -->
        <tinymce v-model="form.html" :config="{}"></tinymce>

        <!-- btn-group -->
        <div class="flex justify-end items-end application-edit__control" :class="[isCollapse ? 'is-collaspe' : 'no-collaspe']">
            <!-- <el-checkbox v-model="form.hide">匿名发布</el-checkbox> -->
            <div class="text-right">
                <!-- <el-button type="success" @click="$refs.channel.open()">频道</el-button> -->
                <el-button type="success" @click="$refs.preview.open(form)">预览</el-button>
                <!-- <el-button type="primary" @click="postData(0)">保存草稿</el-button> -->
                <el-button class="btn-primary" @click="postData(1)">发布</el-button>
            </div>
        </div>

        <!-- 预览 -->
        <preview :source="form" :category-text="categoriesText" :labels="form.labels" ref="preview"></preview>

        <!-- 频道 -->
        <channel :channel-data="category" :channel-selected="channelArray" :labels="form.labels" ref="channel"></channel>
    </el-card>
</template>

<script>
    import Tinymce from '../../components/base/Tinymce';
    import Preview from '../../components/widget/Preview';
    import Channel from '../../components/widget/Channel';
    import FileUpload from '../../components/base/FileUpload';
    import ImgCropperUpload from '../../components/base/ImgCropperUpload';
    import {Cascader, Checkbox, Select} from 'element-ui';
    import {getHelpCategorise} from '../../config/Cache';
    import debounce from 'lodash/debounce';

    export default {
        components: {
            Tinymce,
            Preview,
            Channel,
            FileUpload,
            ImgCropperUpload,
            ElSelect: Select,
            ElCascader: Cascader,
            ElCheckbox: Checkbox,
        },
        data() {
            return {
                form: null,
                types: new Array(1),
                labels: [],
                typeOptions: [],
                options: [],
                isCollapse: document.body.clientWidth < 1024,
                category:[],
                channelArray:[]
            };
        },
        watch: {
            '$route'(val, oldVal) {
                this.createForm();
            }
        },
        computed: {
            titleText() {
                return (this.$route.params.id || this.form.id) ? '编辑' : '发布新';
            },
            categoriesText() {
                return this.types
                    .filter(el => el)
                    .map(ele => this.findName(ele));
            }
        },
        methods: {
            createForm() {
                this.form = {
                    catIds: '', // 类目id    string  多个用,分格
                    catNames: '',  // 类目名称    string  多个用,分格
                    img: '',
                    title: '', // 标题
                    html: '', // 富文本信息   string
                    hide: false, // 是否匿名发布  boolean
                    labels: [], //应用标签    string  多个用,分格
                    audit: 0
                };

                this.types = new Array(1);
            },
            addCategory() {
                if (this.types.length >= 5) {
                    Ele.$message.error('最多添加5个分类');
                    return;
                }

                this.types.push(undefined);
            },
            removeLabel(index) {
                this.labels.splice(index, 1);
            },
            async fetchCategory() {
                const categories = await getHelpCategorise('cascader');
                console.log(categories)
                this.category = categories
                this.typeOptions = categories.map(el => {
                    if (!el.nodes) el.disabled = true;
                    return el;
                });
                this.options = await getHelpCategorise();
            },
            fetchDetail() {
                API.get('help/article/' + this.$route.params.id).then(res => {
                    this.form = res;

                    // 处理html, 移除style标签与样式
                    const regexp = /(<!DOCTYPE html>.*<\/head>)/g;
                    this.form.html = res.html.replace(regexp, '');

                    // for (let key in res) {
                    //     if (this.form.hasOwnProperty(key)) {
                    //         this.form[key] = res[key];
                    //     }
                    // }
                    this.types = res.cats.map(el => this.findCategoryArray(el.catId));
                    //this.labels = res.labels.filter(el => el);
                    //this.form.labels = res.labels.filter(el => el);
                });
            },
            findCategoryArray(sourceId) {
                const options = this.options;
                let arr = [];
                let isFinish = true;
                let id = sourceId;

                while (isFinish) {
                    const element = options.find(el => el.id === id);
                    if (element) {
                        arr.unshift(element.id);
                        if (element.parentid) {
                            id = element.parentid;
                        } else {
                            isFinish = false;
                        }
                    } else {
                        isFinish = false;
                    }
                }
                return arr;
            },
            postData() {
                // 校验： 分类、标题、正文
                if (!this.form.title) return Ele.$message.error('标题不能为空');
                const testTypes = this.types.filter(el => el && el.length);
                if (!testTypes.length) return Ele.$message.error('分类不能为空');
                if (!this.form.html) return Ele.$message.error('正文不能为空');

                // handle data
                const typesArr = this.types.filter(el => el);
                this.form.catIds = typesArr.map(el => el[el.length - 1]).join(',');
                this.form.catNames = typesArr.map(el => {
                    return this.findName(el);
                }).join(',');
                //this.form.audit = audit;

                // handle html img width & height
                if (!this.form.html.includes('<!DOCTYPE html>')) {
                    this.form.html = '<!DOCTYPE html>'
                        + '<html>'
                        + '<head>'
                        + '<meta charset=utf-8>'
                        + '<meta http-equiv=X-UA-Compatible content="IE=edge">'
                        + '<meta name="viewport" content="width=device-width, '
                        + 'initial-scale=1,maximum-scale=1, user-scalable=no">'
                        + '<meta http-equiv=Content-Type content="text/html; charset=UTF-8">'
                        + '<title></title>'
                        + '<style type="text/css">'
                        + '* { font-size: 16px;}'
                        + 'body {line-height: 1.5; font-size: 16px; font-family: -apple-system,SF UI Text,Arial,'
                        + 'Hiragino Sans GB,Microsoft YaHei,WenQuanYi Micro Hei,sans-serif; color: #2f2f2f; }'
                        + 'p, div {line-height: 1.7; text-align: justify;}'
                        + 'p {margin: 0 0 20px; padding-left: 10px; padding-right: 10px;}'
                        + 'iframe { width: 100%;}'
                        + '</style>'
                        + '</head><body>'
                        + this.form.html
                        + '</body></html>'
                }

                const regexp = /(<!DOCTYPE html>.*<\/head>)|(<.*?>)/g;
                this.form.intro = this.form.html
                    .replace(regexp, '')
                    .replace(/^((&nbsp;)|(&ldquo;)|(&rdquo;)|(\n)|(\s)|(↵))*/g, '')
                    .slice(0, 100) + '...';

                const hasId = this.$route.params.id || this.form.id;
                let method = hasId ? 'put' : 'post';
                let url = 'help/article';
                if (hasId) url += '/' + hasId;

                API[method](url, this.form).then(res => {
                    // if (!audit) {
                    //     Ele.$message.success('保存草稿成功');
                    // } else {
                    //     Ele.$message.success('发布新帮助成功');
                    // }
                    if(hasId){
                        Ele.$message.success('发布成功');
                    }else{
                        Ele.$message.success('编辑成功');
                    }
                    

                    if (!hasId) this.form.id = res._id;
                    this.$router.push({name: 'Help.Finish'});
                    // if (audit) {
                    //     if (this.$route.params.id) {
                    //         LocalStore.set('ready_modify_' + this.$route.params.id, 'finish');
                    //     }

                    //     let routerName = 'Help.' + (audit ? 'Wait' : 'Ready');
                    //     this.$router.push({name: routerName});
                    // }

                    const regexp = /(<!DOCTYPE html>.*<\/head>)/g;
                    this.form.html = this.form.html.replace(regexp, '');
                });
            },
            findName(array) {
                return this.options.find(el => el.id === array[array.length - 1]).text;
            },
        },
        mounted() {
            bus.$on('collapse-observe', (value) => {
              // ...
                console.log('collapse-observe', value);
                this.isCollapse = value;
            })
        },
        created() {
            this.createForm();
            if (this.$route.params.id) this.fetchDetail();
        },
        beforeRouteEnter(to, from, next) {
            next(vm => {
                vm.fetchCategory();
            });
        }
    };
</script>

<style lang="scss">
    .application-edit {
        .el-card__body {
            padding-bottom: 80px;
        }

        header {
            color: #333;
            font-size: 20px;
        }

        &__upload {
            max-height: 250px;
            margin: 18px auto 12px;

            .default {
                color: #999;
                height: 150px;
                font-size: 14px;
                padding-top: 30px;
                background-color: #ececec;

                .iconfont {
                    font-size: 40px;
                }
            }

            .active {
                // height: 500px;
                text-align: center;

                .delete-icon {
                    position: absolute;
                    right: -15px;
                    top: -12px;
                    background: #fff;
                    border-radius: 50%;

                    .el-icon-error {
                        color: #666;
                        font-size: 30px;
                    }
                }
            }
        }

        &__title {
            width: 100%;
            height: 46px;
            font-size: 22px;
            line-height: 46px;
            margin-bottom: 20px;
            &::placeholder-text {
                color: #999;
            }
        }

        &__tags {
            width: 100%;
            min-height: 40px;
            font-size: 16px;
            line-height: 40px;
            margin-bottom: 20px;

            .el-input__inner {
                border: 0;
                border-radius: 0;
            }

            &.el-select .el-tag {
                padding: 4px 10px;
                height: 32px;
                font-size: 13px;
            }

            .el-input__suffix {
                display: none;
            }
        }

        &__control {
            position: fixed;
            bottom: 21px;
            background: #fff;
            padding: 1rem;
            transition: all .6s;

            &.is-collaspe {
                width: calc(100% - 130px);
                left: 110px;
            }

            &.no-collaspe {
                width: calc(100% - 330px);
                left: 300px;
            }
        }
    }
</style>
